<?php

namespace falcon5\inc\Helpers;

use falcon5\inc\Exceptions\InvalidArgumentException;

class HttpRequestHelper
{
    /**
     * 获取请求Header 、
     * @param array $headers
     * @return array
     * @throws InvalidArgumentException
     */
    public static function getAllHeaders(array $headers = []): array
    {
        $request_headers = [];
        foreach($_SERVER as $key => $value) {
            if (substr($key, 0, 5) == "HTTP_") {
                $key = str_replace(" ", "-", ucwords(strtolower(str_replace("_", " ", substr($key, 5)))));
                $request_headers[$key] = $value;
            } else if ($key == "CONTENT_TYPE") {
                $request_headers["Content-Type"] = $value;
            }
        }

//        $lang = UrlHelper::getCurrentLang();
//        $urlMode = falcon5_app(WPOption::class)->getUrlMode();
//        if ($urlMode === WPUrlMode::URL_MODE_SUBDOMAIN) {
//            // 子域名模式
//            $host = $lang . '.' . preg_replace('/^[^.]+\.(.+)$/', '$1', $_SERVER['HTTP_HOST']);
//        } else {
//            // 子目录模式
//            $host = $_SERVER['HTTP_HOST'];
//        }

//        $request_headers['Host'] = $host;

        // proxy 模式不能带上host，会导致/proxy 请求404
        if(isset($request_headers['HOST'])) unset($request_headers['HOST']);
        if(isset($request_headers['host'])) unset($request_headers['host']);
        if(isset($request_headers['Host'])) unset($request_headers['Host']);

        // proxy 模式不带上content-length，可能会导致页面一直等待响应
        if (isset($headers['Content-Length'])) unset($headers['Content-Length']);

        if(!function_exists('gzdecode')) {
            $request_headers['Accept-Encoding'] = '';
        } else {
            $request_headers['Accept-Encoding'] = 'gzip';
        }

        if(isset($request_headers['accept-encoding'])) {
            unset($request_headers['accept-encoding']);
        }

        if(isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) {
            $request_headers['Authorization'] = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
            if(isset($request_headers['authorization'])) {
                unset($request_headers['authorization']);
            }
        }

        if(isset($request_headers['content-type'])) {
            $request_headers['Content-Type'] = $request_headers['content-type'];
            unset($request_headers['content-type']);
        }

        if(isset($request_headers['Content-Type']) && strpos($request_headers['Content-Type'], 'multipart/form-data;') !== false) {
            $request_headers['Content-Type'] = 'application/x-www-form-urlencoded';
            $request_headers['Content-Length'] = '';

            if(isset($request_headers['content-length'])) {
                unset($request_headers['content-length']);
            }
        }

        return apply_filters('falcon5_proxy_all_headers', array_merge($request_headers, $headers));
    }
}